package com.szc.fs.service.imp;

import cn.hutool.core.date.DateUtil;
import cn.hutool.http.HttpRequest;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.szc.fs.config.JQRConstants;
import com.szc.fs.mapper.NewsInfoMapper;
import com.szc.fs.mapper.NewsRobotMapper;
import com.szc.fs.pojo.NewsInfo;
import com.szc.fs.pojo.NewsRobot;
import com.szc.fs.pojo.message.*;
import com.szc.fs.service.NewsInfoService;
import com.szc.fs.service.NewsRobotService;
import com.szc.fs.util.MessageUtil;
import com.szc.fs.util.PropertiesUtil;
import com.szc.fs.util.Result;
import com.szc.fs.util.TokenUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.thymeleaf.util.StringUtils;

import javax.xml.transform.Source;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.util.List;
import java.util.stream.Collectors;

/**
 * ClassName: DatabasesDetailController
 * DesCriotion: 发送新闻消息推送
 * Author: tianliuyang
 * Date: 2022/12/29 10:09
 * Version: 1.0
 */

@Service
public class NewsInfoServiceImp extends ServiceImpl<NewsInfoMapper, NewsInfo> implements NewsInfoService {
    private static final Logger LOGGER = LoggerFactory.getLogger(NewsInfoServiceImp.class);
    @Autowired
    private NewsRobotService newsRobotService;

    @Override
    public String pushMsg() throws NoSuchAlgorithmException, InvalidKeyException {
        QueryWrapper<NewsInfo> objectQueryWrapper = new QueryWrapper<>();
        objectQueryWrapper.in("push_status", 0);
        objectQueryWrapper.last("limit 5");
        objectQueryWrapper.orderByAsc("submit_date");
        List<NewsInfo> list = this.list(objectQueryWrapper);
//        消息数量不满足5条或者没有可推送的消息则不推送
        if (list == null || list.size() < 5) {
            LOGGER.info("可用新闻不足5条，今日不推送,可用条数为:"+list.size()+" ,详情为："+ JSON.toJSONString(list));
            return null;
        }
//        获取新闻的机器人列表
        QueryWrapper<NewsRobot> newsRobotQueryWrapper = new QueryWrapper<>();
        newsRobotQueryWrapper.eq("send_type", "news").eq("robot_status", 0);
        List<NewsRobot> robots = newsRobotService.list(newsRobotQueryWrapper);
        MessageContent messageContent = MessageUtil.getMessageContent(list);
        String resultMsg = "";
        boolean sendFlag = true;
        for (NewsRobot robot : robots) {
            long timestamp = DateUtil.currentSeconds();
            String token = TokenUtil.getToken(timestamp, robot.getRobotSecret());
            Message message = new Message(JSON.toJSONString(messageContent), JQRConstants.JQR_MSG_TYPE_INTERACTIVE, String.valueOf(timestamp), token);
            String body = HttpRequest.post(robot.getRobotWebhook())
                    .body(JSON.toJSON(message).toString()).execute().body();
            JSONObject result = JSON.parseObject(body);
            LOGGER.info(robot.getRemark() + "    " + JSON.toJSON(message).toString() + "    "+body);
            if (result.getInteger("code") == 0) {
                resultMsg += robot.getRemark() +" 群组发送消息成功；";
            }else{
                resultMsg += robot.getRemark() +" 群组发送消息失败："+
                        result.getInteger("code")+",message:" + result.getInteger("msg");
                sendFlag = false;
            }
        }
////        推送成功后更新状态和推送时间
        if (sendFlag){
//            更新已同步的数据
            UpdateWrapper<NewsInfo> objectUpdateWrapper = new UpdateWrapper<>();
            objectUpdateWrapper.in("id",list.stream().map(a -> a.getId()).collect(Collectors.toList()));
            objectUpdateWrapper.set("push_status",1);
            objectUpdateWrapper.set("push_date",DateUtil.now());
            this.update(null,objectUpdateWrapper);
        }
        LOGGER.info(" 返回结果："+resultMsg);
        return resultMsg;
    }

    @Override
    public Result submit(String requestBody) {
        NewsInfo newsInfo = JSON.parseObject(requestBody, NewsInfo.class);
        if (newsInfo == null || StringUtils.isEmptyOrWhitespace(newsInfo.getSubmitUser()) ||
                StringUtils.isEmptyOrWhitespace(newsInfo.getTitle()) ||
                StringUtils.isEmptyOrWhitespace(newsInfo.getUrl())) {
            return Result.fail("参数异常");
        }
        newsInfo.setSubmitDate(DateUtil.now());
        return this.save(newsInfo) ? Result.ok() : Result.fail();

    }

    @Override
    public JSONObject check(String title, String url) {
        QueryWrapper<NewsInfo> objectQueryWrapper = new QueryWrapper<>();
        if (!StringUtils.isEmptyOrWhitespace(title)) {
            objectQueryWrapper.in("title", title);
        } else if (!StringUtils.isEmptyOrWhitespace(url)) {
            objectQueryWrapper.in("url", url);
        }
        List<NewsInfo> list = this.list(objectQueryWrapper);
        JSONObject object = new JSONObject();
        object.put("valid", list.size() == 0 ? true : false);
        ;
        return object;

    }

}
